package org.sam.swing.table.action;

import java.awt.event.ActionEvent;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.RowFilter;
import javax.swing.table.TableModel;

import org.apache.commons.lang3.tuple.Pair;
import org.jdesktop.swingx.JXTable;
import org.sam.swing.resource.ResourceLoader;
import org.sam.swing.table.model.FilterObject;
import org.sam.swing.table.model.FilterOperation;
import org.sam.swing.table.tools.JDialogFilter;

/**
 * 表格数据过滤操作对象
 * 
 * @author sam
 *
 */
public class JSTableFitlerAction extends JSTableBaseAction implements FilterOperation {

	private static final long serialVersionUID = 1130063140609825326L;

	/**
	 * 表格数据过滤操作对象
	 * 
	 * @param table
	 */
	public JSTableFitlerAction(JXTable table) {
		super(table);
		this.putValue(AbstractAction.NAME, "过滤");
		this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ResourceLoader.getResource(ResourceLoader.IMAGE_FIND)));
		this.putValue(SHORT_DESCRIPTION, "过滤数据设置");
	}

	/**
	 * 过滤对象数据
	 */
	private List<FilterObject> filters;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<FilterObject> getFilterObjects() {
		return this.filters;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setFilterObjects(List<FilterObject> fitlers) {
		this.filters = fitlers;
	}

	/**
	 * 执行操作
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			Pair<String, List<FilterObject>> result = JDialogFilter.showFilterDialogWidthAction(this.getTable(),
					this.getFilterObjects());
			
			if (JDialogFilter.OK.equals(result.getKey())){
				this.setFilterObjects(result.getValue());
				
				RowFilter<? super TableModel, ? super Integer> filter = FilterOperation
						.getRowFilterSimple(this.getTable().getModel(), this.getTable().getColumnModel(), result.getValue());
				
				this.getTable().setRowFilter(filter);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
